﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MedicalSystem.SmartReport.Access;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using MedicalSystem.SmartReport.Viewer;
using MedicalSystem.SamrtReport.Library;


namespace MedicalSystem.SamrtReport.Tools
{
    public partial class DataSettingWizard : Form
    {
        public DataSettingWizard()
        {
            InitializeComponent();
        }

        private bool _selectDatabase = false;
        private string _providerName = string.Empty;
        private IDatabase _database = null;

        private void DataSettingWizard_Load(object sender, EventArgs e)
        {
            this.tabControl1.TabPages.Clear();
            this.tabControl1.TabPages.Add(this.SelectDataTypetabPage);

            this.comboBox1.Items.Clear();
            for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
            {
                this.comboBox1.Items.Add(ConfigurationManager.ConnectionStrings[i].Name);
            }
            CustomFormHepler.ShowForm(this);
        }

        private void DatabaseButton_Click(object sender, EventArgs e)
        {
            _selectDatabase = true;
            this.richTextBox.Text = "允许您连接到数据库并为您的表单设计器选择数据库对象。此选项会创建一个数据集到设计器中。";
            this.NextButton.Enabled = true;
            
          
        }

        private void ObjectButton_Click(object sender, EventArgs e)
        {
            _selectDatabase = false;
            this.richTextBox.Text = "允许您选择一个包含强类型数据集合的对象。此选项会添加一个已有的数据集到设计器中。";
            this.NextButton.Enabled = true;
          
           
        }

        private void NextButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab == this.SelectDataTypetabPage)
            {
                if (_selectDatabase)
                {
                    this.TitleLabel.Text = "选择您的数据连接";
                    this.tabControl1.TabPages.Clear();
                    this.tabControl1.TabPages.Add(this.SelectConnTabpage);
                    this.NextButton.Enabled = false;
                    this.PreviousButton.Enabled = true;
                }
                else
                {
                    this.TitleLabel.Text = "选择希望绑定到的对象";
                    this.tabControl1.TabPages.Clear();
                    this.tabControl1.TabPages.Add(this.SelectObjectTabPage);
                    this.NextButton.Enabled = false;
                    this.PreviousButton.Enabled = true;
                }
            }
            else if (this.tabControl1.SelectedTab == this.SelectConnTabpage)
            {
                MethodInvoker methodInvoker = new MethodInvoker(InitalizeDataTableList);
                this.BeginInvoke(methodInvoker);

                this.TitleLabel.Text = "选择数据库表";
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectTableTabPage);
                this.NextButton.Enabled = false;
                this.PreviousButton.Enabled = true;
            }
        }
        private void InitalizeDataTableList()
        {
            _database = DatabaseFactory.CreateDatabase(this.richTextBox1.Text, this._providerName);
            this.FinishButton.Enabled = false;
           
            try
            {
                using (AsyncWorker asyncWorker = new AsyncWorker(this.checkedListBox1))
                {
                    asyncWorker.DoWork += delegate(object sender, DoWorkEventArgs e)
                    {
                        e.Result = _database.GetDataTableNames();
                    };
                    asyncWorker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        DataTable tableName = e.Result as DataTable;
                        this.checkedListBox1.Items.Clear();
                        foreach (DataRow dr in tableName.Rows)
                        {
                            this.checkedListBox1.Items.Add(dr[0].ToString(), false);
                        }
                        this.FinishButton.Enabled = this.checkedListBox1.Items.Count > 0;
                    };
                    asyncWorker.Run();
                }

            }
            catch (SmartReportException e)
            {
                this.FinishButton.Enabled = false;
                Trace.WriteLine(e.InnerException.Message, "Error");
            }
           
        }
        private void NewConnectionButton_Click(object sender, EventArgs e)
        {
            DataConnectionSettingFrm dataConnectionSetting = new DataConnectionSettingFrm();
            if (dataConnectionSetting.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dataConnectionSetting.ConnectionStringName))
                {
                    this.comboBox1.Items.Add(dataConnectionSetting.ConnectionStringName);
                    this.comboBox1.Text = dataConnectionSetting.ConnectionStringName;
                }

                this.richTextBox1.Text = dataConnectionSetting.ConnectionString;
                this._providerName = dataConnectionSetting.ProviderName; ;
                this.NextButton.Enabled = true;
               
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.comboBox1.Text))
            {
                this.richTextBox1.Text = string.Empty;
                this.NextButton.Enabled = false;
                return;
            }
            if (ConfigurationManager.ConnectionStrings[this.comboBox1.Text] != null)
            {
                this.richTextBox1.Text = ConfigurationManager.ConnectionStrings[this.comboBox1.Text].ConnectionString;
                this._providerName = ConfigurationManager.ConnectionStrings[this.comboBox1.Text].ProviderName;
                this.NextButton.Enabled = true;
            }
          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.richTextBox1.Visible == false)
            {
                this.richTextBox1.Visible = true;
                this.button2.Text = "-";
            }
            else
            {
                this.richTextBox1.Visible = false;
                this.button2.Text = "+";
            }
        }

        private void PreviousButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab == this.SelectConnTabpage)
            {
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectDataTypetabPage);
                this.TitleLabel.Text = "选择数据源类型";
                this.PreviousButton.Enabled = false;
                this.NextButton.Enabled = true;
                
            }
            else if (this.tabControl1.SelectedTab == this.SelectTableTabPage)
            {
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectConnTabpage);
                this.TitleLabel.Text = "选择您的数据连接";
                this.PreviousButton.Enabled = true;
                this.NextButton.Enabled = true;
            }
            else if (this.tabControl1.SelectedTab == this.SelectObjectTabPage)
            {
                this.tabControl1.TabPages.Clear();
                this.tabControl1.TabPages.Add(this.SelectDataTypetabPage);
                this.TitleLabel.Text = "选择数据源类型";
                this.PreviousButton.Enabled = false;
                this.NextButton.Enabled = true;
            }
        }

        private void FinishButton_Click(object sender, EventArgs e)
        {
            this.DfaultErrorProvider.Clear();
          
            if (this.tabControl1.SelectedTab == this.SelectTableTabPage)
            {
                if (this.checkedListBox1.CheckedItems.Count == 0)
                {
                    this.DfaultErrorProvider.SetError(this.label4, "您当前还未选择任何数据表");
                    return;
                }
                if (string.IsNullOrEmpty(this.DataSetLogicNameTextBox.Text))
                {
                    this.DfaultErrorProvider.SetError(this.DataSetLogicNameTextBox, "请输入一个数据源的逻辑名称,建议使用产品的名称命名此数据源");
                    return;
                }
               
                IList<string> tables = new List<string>();
                for (int i = 0; i < this.checkedListBox1.CheckedItems.Count; i++)
                {
                    tables.Add(this.checkedListBox1.CheckedItems[i].ToString());
                }
                string dataBaseName = this.DataSetLogicNameTextBox.Text;
                try
                {
                    _database.SaveDataSchema(tables, string.Format(@"{0}\{1}.xml", BindingData.Path, dataBaseName));
                }
                catch (Exception ex)
                {

                    Trace.WriteLine(string.Format("未能导入数据源,发生以下错误:{0}", ex.Message), "Error");
                }
               
                Trace.WriteLine(string.Format("已添加新数据源{0}到设计器中,可在绑定数据源窗口浏览此数据源", dataBaseName));

            }
            else if (this.tabControl1.SelectedTab == this.SelectObjectTabPage)
            {
                if (this.checkedListBox2.CheckedItems.Count == 0)
                {
                    this.DfaultErrorProvider.SetError(this.checkedListBox2, "您当前还未选择任何对象");
                    return;
                }
                if (string.IsNullOrEmpty(this.LogicNametTextBox.Text))
                {
                    this.DfaultErrorProvider.SetError(this.LogicNametTextBox, "请输入一个数据源的逻辑名称,建议使用产品的名称命名此数据源");
                    return;
                }
                DataSet ds = new DataSet();
                for (int i = 0; i < this.checkedListBox2.CheckedItems.Count; i++)
                {
                    CheckListBoxItem item = this.checkedListBox2.CheckedItems[i] as CheckListBoxItem;
                    ds.Tables.Add(item.Data as DataTable);
                }
                string dataBaseName = this.LogicNametTextBox.Text;

                ds.WriteXmlSchema(string.Format(@"{0}\{1}.xml", BindingData.Path, dataBaseName));

                Trace.WriteLine(string.Format("已添加新数据源{0}到设计器中,可在绑定数据源窗口浏览此数据源", dataBaseName));
            }

            this.DialogResult = DialogResult.OK;
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void ImportAssemblyButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "程序集文件(*.dll)|*.dll";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string assemblyName = openFileDialog.FileName;
                LoadAssembly(assemblyName);
            }
        }

        private void LoadAssembly(string path)
        {
            Assembly assembly = Assembly.LoadFile(path);
            if (assembly == null)
            {
                Trace.WriteLine(string.Format("未能加载程序集{0}", Path.GetFileName(path)));
                return;
            }

           Type[] Types= assembly.GetTypes();
           this.checkedListBox2.Items.Clear();
           foreach (Type t in Types)
           {
               if (typeof(DataTable).IsAssignableFrom(t))
               {
                   CheckListBoxItem item = new CheckListBoxItem();
                   item.DisplayName = t.Name;
                   item.Data = Activator.CreateInstance(t);
                   this.checkedListBox2.Items.Add(item, false);
               
               }
           }
           this.FinishButton.Enabled = this.checkedListBox2.Items.Count > 0;
        }
    }
    public class CheckListBoxItem
    {
        string _displayName;
        object _data;

        public string DisplayName
        {
            get { return _displayName; }
            set { _displayName = value; }
        }
        public object Data
        {
            get { return _data; }
            set { _data = value; }
        }
        public override string ToString()
        {
            return _displayName;
        }
    }
}
